//基于数组实现队列

class MyblockingQueue{
    private  int[] item=new int[1000];
    //约定[head,tail)的队列有效数字
    volatile private int head;
    volatile private int tail;
    volatile private int size;

    //入队列
    synchronized public void put(int elem) throws InterruptedException {
        //如果满了就返回
        if(size==item.length)
        {
            //return;
            this.wait();
        }
        //新元素放到tail位置上
        item[tail]=elem;
        tail++;
        //判断是否满了
        if(size==item.length)
        {
            //万一tail达到末尾,就从0开始
            tail=0;
        }
        //个数加一
        size++;
        this.notify();
    }
//出队列
    synchronized public Integer take() throws InterruptedException {
        if(size==0)
        {
            //return null;
            this.wait();
        }
        int value=item[head];
        head++;
        if(head==item.length)
        {
            head=0;
        }
        size--;
        this.notify();
        return value;
    }
}
public class ThreadDemo17 {
    public static void main(String[] args) {
        MyblockingQueue queue=new MyblockingQueue();

        Thread t1=new Thread( ()->{
            while(true)
            {
                int value= 0;
                try {
                    value = queue.take();
                    System.out.println("消费者是:"+ value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        t1.start();
        //生产者
        Thread t2=new Thread( ()-> {
            int value=0;
            while(true)
            {
                try {
                    System.out.println("生产者是:"+value);
                    queue.put(value);
                    value++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        t2.start();


    }
}

